<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import { ElMessage, type FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import {apiEditPassword, apiEditUser, apiEnroll, apiGetSecretSecurity} from '@/api/user'

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const action = ref({
  type: 1,
  label: '登 录'
}) // 1为登录，2为注册，3为获取密保信息, 4为重置

const ruleForm = reactive({
  username: "admin",
  password: "admin123",
  question1: "",
  answer1: "",
  question2: "",
  answer2:""
});

const resetForm = () => {
  ruleForm.username = ""
  ruleForm.password = ""
  ruleForm.question1 = ""
  ruleForm.answer1 = ""
  ruleForm.question2 = ""
  ruleForm.answer2 = ""
}

const changeStatus = (target) => {
  action.value.type = target
  target === 1?action.value.label = "登录":target === 2?action.value.label = "注册":action.value.type===3?action.value.label="搜索":action.value.label = "重置"
}

const onGetSecretSecurity = async () => {
  loading.value = true;

  const res = await apiGetSecretSecurity({ "username": ruleForm.username })
  if (res.code === 200) {
    let data = res.data
    ruleForm.question1 = data.question1
    ruleForm.question2 = data.question2
    changeStatus(4)
  }
  loading.value = false

}

const onResetPassword = async () => {
  const res = await apiEditPassword({
    username: ruleForm.username,
    question1: ruleForm.question1,
    answer1: ruleForm.answer1,
    question2: ruleForm.question2,
    answer2:ruleForm.answer2
  })
  if (res.code === 200) {
    ElMessage({
      message: res.message,
      type: 'success'
    })
    ruleForm.password = "123456"
    changeStatus(1)
  }
}

const toSure = async(formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (action.value.type === 1) {
        onLogin()
      } else if (action.value.type === 2) {
        onEnroll()
      } else if (action.value.type === 3) {
        onGetSecretSecurity()
      } else if (action.value.type === 4) {
        onResetPassword()
      }
    }
  })
}

const onEnroll = async () => {
  const res = await apiEnroll({
    username: ruleForm.username,
    password: ruleForm.password,
    question1: ruleForm.question1,
    answer1: ruleForm.answer1,
    question2: ruleForm.question2,
    answer2:ruleForm.answer2
  })
  if (res.code === 200) {
    ElMessage({
      message: '注册成功',
      type: 'success'
    })
    changeStatus(1)
  }
}

const onLogin = async () => {
  loading.value = true;
  useUserStoreHook()
    .loginByUsername({ username: ruleForm.username, password: ruleForm.password })
    .then(res => {
      console.log(res)
      if (res.code === 200) {
        // 获取后端路由
        return initRouter().then(() => {
          router.push(getTopMenu(true).path).then(() => {
            message("登录成功", { type: "success" });
          });
        });
      }
    })
    .finally(() => (loading.value = false));
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    toSure(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: 'PLEASE INPUT USERNAME',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="USERNAME"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150" v-if="action.type !==3 && action.type !== 4">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150" v-if="action.type !== 1">
              <el-form-item prop="question1">
                <el-col :span="14">
                  <el-input
                    v-model="ruleForm.question1"
                    :disabled="action.type===3 || action.type === 4"
                    clearable
                    placeholder="密保信息1"
                  />
                </el-col>
                <el-col :span="8" :offset="2">
                  <el-input
                    v-model="ruleForm.answer1"
                    clearable
                    placeholder="回答1"
                  />
                </el-col>
              </el-form-item>
            </Motion>

            <Motion :delay="150" v-if="action.type !== 1">
              <el-form-item prop="question2">
                <el-col :span="14">
                  <el-input
                    v-model="ruleForm.question2"
                    :disabled="action.type===3 || action.type === 4"
                    clearable
                    placeholder="密保信息2"
                  />
                </el-col>
                <el-col :span="8" :offset="2">
                  <el-input
                    v-model="ruleForm.answer2"
                    clearable
                    placeholder="回答2"
                  />
                </el-col>
              </el-form-item>
            </Motion>
            <!-- <Motion :delay="150">
              
            </Motion> -->

            <Motion :delay="250">
              <div class="relative" style="top:-14px;">
                <div class="w-full flex justify-between items-center">
                  <div v-if="action.type !== 1"><el-link class="mx-1" type="primary" size="small" @click="changeStatus(1)">登 录</el-link></div>
                  <div v-if="action.type !== 2"><el-link class="mx-1" type="primary" size="small" @click="changeStatus(2)">注 册</el-link></div>
                  <div v-if="action.type !==3 && action.type !== 4"><el-link class="mx-1" type="danger" size="small" @click="changeStatus(3)">忘记密码?</el-link></div>
                </div>
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="toSure(ruleFormRef)"
                >
                  {{ action.label }}
                </el-button>
              </div>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
